package org.dromara.business.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.transaction.Transaction;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.SysUser;
import org.springframework.stereotype.Service;
import org.dromara.business.domain.bo.StakingProductBo;
import org.dromara.business.domain.vo.StakingProductVo;
import org.dromara.business.domain.StakingProduct;
import org.dromara.business.mapper.StakingProductMapper;
import org.dromara.business.service.IStakingProductService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.rmi.server.ServerCloneException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Collection;

/**
 * 质押产品Service业务层处理
 *
 * @author Eric
 * @date 2025-09-05
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class StakingProductServiceImpl implements IStakingProductService {

    private final StakingProductMapper baseMapper;
    private final StakingContractsService stakingContractsService;

    /**
     * 查询质押产品
     *
     * @param id 主键
     * @return 质押产品
     */
    @Override
    public StakingProductVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询质押产品列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 质押产品分页列表
     */
    @Override
    public TableDataInfo<StakingProductVo> queryPageList(StakingProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<StakingProduct> lqw = buildQueryWrapper(bo);
        Page<StakingProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的质押产品列表
     *
     * @param bo 查询条件
     * @return 质押产品列表
     */
    @Override
    public List<StakingProductVo> queryList(StakingProductBo bo) {
        LambdaQueryWrapper<StakingProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<StakingProduct> buildQueryWrapper(StakingProductBo bo) {
        LambdaQueryWrapper<StakingProduct> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(StakingProduct::getId);
        lqw.like(StringUtils.isNotBlank(bo.getProductName()), StakingProduct::getProductName, bo.getProductName());
        lqw.eq(StringUtils.isNotBlank(bo.getProductCode()), StakingProduct::getProductCode, bo.getProductCode());
        lqw.eq(bo.getPeriodDays() != null, StakingProduct::getPeriodDays, bo.getPeriodDays());
        lqw.eq(bo.getDailyRate() != null, StakingProduct::getDailyRate, bo.getDailyRate());
        lqw.eq(bo.getMinAmount() != null, StakingProduct::getMinAmount, bo.getMinAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), StakingProduct::getDescription, bo.getDescription());
        lqw.eq(bo.getStatus() != null, StakingProduct::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增质押产品
     *
     * @param bo 质押产品
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(StakingProductBo bo) {
        StakingProduct add = MapstructUtils.convert(bo, StakingProduct.class);
        validEntityBeforeSave(add);
        add.setCreateTime(LocalDateTime.now());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        return flag;
    }

    public void fundReward(BigDecimal amount){
        try{
            BigInteger realAmount = amount.multiply(new BigDecimal("1000000000000000000")).setScale(0, RoundingMode.DOWN).toBigInteger();
            stakingContractsService.fundReward(realAmount);
        }catch (Exception e){
            throw new ServiceException("添加收益合约调用异常："+e.getMessage());
        }
    }

    /**
     * 修改质押产品
     *
     * @param bo 质押产品
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(StakingProductBo bo) {
        StakingProduct update = MapstructUtils.convert(bo, StakingProduct.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(StakingProduct entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除质押产品信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changeProductStatus(Long id, Integer status) {
        StakingProduct product = baseMapper.selectById(id);
        Long lockDuration = Convert.toLong(product.getPeriodDays())*24*60*60;
//        if(add.getPeriodDays() == 1){
//            lockDuration = 0L;
//        }
        Long dailyRate = product.getDailyRate().multiply(BigDecimal.TEN.multiply(BigDecimal.TEN)).setScale(0, RoundingMode.DOWN).longValue();
        try {
            String hash = stakingContractsService.editProduct(BigInteger.valueOf(product.getId()), BigInteger.valueOf(lockDuration), BigInteger.valueOf(dailyRate),
                product.getMinAmount(), true, status==1);
            log.info(StrUtil.format("hash:{}", hash));
        }catch (Exception e){
            throw new ServiceException("添加商品合约调用异常："+e.getMessage());
        }
        return baseMapper.update(null,
            new LambdaUpdateWrapper<StakingProduct>()
                .set(StakingProduct::getStatus, status)
                .eq(StakingProduct::getId, id)) > 0;
    }

    @Override
    public List<StakingProduct> getList() {
        LambdaQueryWrapper<StakingProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StakingProduct::getStatus, 1);
        wrapper.orderByAsc(StakingProduct::getSort);
        return baseMapper.selectList(wrapper);
    }
}
